package com.music.mysongs.fragment.option

import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.music.mysongs.R
import com.music.mysongs.helper.myActReadStringSPF
import com.music.mysongs.utils.myLog
import com.music.mysongs.utils.myToast
import kotlinx.android.synthetic.main.fragment_song_msg.*
import java.io.*
import java.net.Socket

class SongMsgFragment : Fragment() {
    private val mTag = "SongMsgFragment"
    private var mName: String? = null

    //Comment model
    private var mSocket: Socket? = null
    private var mRead: BufferedReader? = null
    private var mWrite: PrintWriter? = null
    private val port: Int = 8080
    private val host: String = "192.168.43.164"//10.100.48.233
    private val sb = StringBuilder()
    private var isRun = false

    private val myHandler: Handler = Handler {
        //socket model
        txtShow_msg.text = it.obj.toString()
        editWord_msg.text = null
        false
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        return inflater.inflate(R.layout.fragment_song_msg, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mName = myActReadStringSPF(this.activity, "spfUserName")
        //socket server
        object : Thread() {
            override fun run() {
                try {
                    mSocket = Socket(host, port)
                    if (mSocket == null) {
                        isRun = false
                        myToast(context!!, "未连上服务器端口")
                    } else {
                        isRun = true
                        mRead =
                            BufferedReader(InputStreamReader(mSocket?.getInputStream(), "UTF-8"))
                        mWrite = PrintWriter(
                            BufferedWriter(
                                OutputStreamWriter(
                                    mSocket?.getOutputStream()
                                )
                            ), true
                        )
                        Thread(MyReceive()).start()
                    }
                } catch (e: IOException) {
                    isRun = false
                    e.printStackTrace()
                }
            }
        }.start()
        btnSend_msg.setOnClickListener {
            if (!editWord_msg.text.isNullOrEmpty() && mSocket!!.isConnected && !mSocket!!.isOutputShutdown) {
                val mSend = editWord_msg.text.toString()
                mWrite!!.println("$mName: $mSend")
                myLog("$mTag: sb=$sb")
            }
        }
    }

    internal inner class MyReceive : Runnable {
        override fun run() {
            while (isRun) {
                try {
                    if (mSocket!!.isConnected && !mSocket!!.isInputShutdown) {
                        sb.append("\n")
                        if (mRead?.readLine().also { sb.append(it + "\n") } != null) {
                            val msg = Message()
                            msg.obj = sb
                            myHandler.sendMessage(msg)
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
}